package com.example.work2;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MusicActivity extends AppCompatActivity {

    private Button button2,button3,button4,button5;
    Context context;
    private MyService.Mybinder mybinder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music);
        Intent intent=new Intent(MusicActivity.this,MyService.class);
        button2=findViewById(R.id.button2);
        button3=findViewById(R.id.button3);
        button4=findViewById(R.id.button4);
        button5=findViewById(R.id.button5);
        ServiceConnection connection=new ServiceConnection() {
            @Override
            //通过返回ibinder，播放音乐，执行myplay()函数
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                //将iBinder传给在MusicActivity中的Mybinder实例对象,强制性的类型转换
                Log.d("生命周期状态：","onBind...");
                mybinder=(MyService.Mybinder)iBinder;
                mybinder.myplay();
            }
            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                Log.d("生命周期状态：","unBind...");
                mybinder=null;//解绑
            }
        };

        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d("生命周期状态：","StartService...");
                startService(intent);
            }
        });

        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d("生命周期状态：","StopService...");
                stopService(intent);
            }
        });

        button4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //connection是一个接口，规定了两个动作，绑定与解绑
                bindService(intent,connection, Context.BIND_ABOVE_CLIENT);
            }
        });

        button5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                unbindService(connection);
            }
        });

    }
}